import axios from 'axios';
import { configService } from '../../services/config-service';

export class SingleConvert {
  constructor() {
    this.selectedFile = null;
    this.sourceFormat = '';
    this.targetFormat = '';
    this.isConverting = false;
    this.convertProgress = 0;
    this.convertResult = null;
    this.errorMessage = '';
    this.isLoading = true;
    
    this.formats = [];
    this.conversionOptions = {
      addTitle: false,
      preserveLineBreaks: true,
      addPageBreaks: false
    };

    this.init();
  }

  async init() {
    try {
      await configService.loadConfig();
      this.formats = configService.getSupportedFormats();
      this.isLoading = false;
    } catch (error) {
      console.error('初始化失败:', error);
      this.errorMessage = '初始化失败，请刷新页面重试';
      this.isLoading = false;
    }
  }

  onFileSelected(event) {
    const file = event.target.files[0];
    if (file) {
      this.validateAndSetFile(file);
    }
  }

  validateAndSetFile(file) {
    // 检查文件大小
    if (file.size > configService.getMaxFileSize()) {
      this.errorMessage = `文件大小超过限制 (${configService.getMaxFileSizeFormatted()})`;
      return;
    }

    // 检查文件格式
    const extension = file.name.split('.').pop().toLowerCase();
    if (!configService.isFormatSupported(extension)) {
      this.errorMessage = `不支持的文件格式: .${extension}`;
      return;
    }

    this.selectedFile = file;
    this.sourceFormat = extension;
    this.convertResult = null;
    this.errorMessage = '';
  }

  onDragOver(event) {
    event.preventDefault();
    event.dataTransfer.dropEffect = 'copy';
  }

  onDrop(event) {
    event.preventDefault();
    const files = event.dataTransfer.files;
    if (files.length > 0) {
      this.validateAndSetFile(files[0]);
    }
  }

  getAvailableTargetFormats() {
    if (!this.sourceFormat) return [];
    const availableFormats = configService.getAvailableTargetFormats(this.sourceFormat);
    return this.formats.filter(format => availableFormats.includes(format.value));
  }

  async convertFile() {
    if (!this.selectedFile || !this.sourceFormat || !this.targetFormat) {
      this.errorMessage = '请选择文件和转换格式';
      return;
    }

    this.isConverting = true;
    this.convertProgress = 0;
    this.errorMessage = '';
    this.convertResult = null;

    try {
      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('source_format', this.sourceFormat);
      formData.append('target_format', this.targetFormat);
      formData.append('options', JSON.stringify(this.conversionOptions));

      // 模拟进度更新
      const progressInterval = setInterval(() => {
        if (this.convertProgress < 90) {
          this.convertProgress += 10;
        }
      }, 200);

      const response = await axios.post(`${configService.getApiBaseUrl()}/convert`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        responseType: 'blob'
      });

      clearInterval(progressInterval);
      this.convertProgress = 100;

      // 创建下载链接
      const blob = new Blob([response.data]);
      const url = window.URL.createObjectURL(blob);
      const originalName = this.selectedFile.name.split('.')[0];
      const downloadName = `${originalName}_converted.${this.targetFormat}`;

      this.convertResult = {
        downloadUrl: url,
        filename: downloadName,
        size: configService.formatFileSize(blob.size)
      };

    } catch (error) {
      this.errorMessage = error.response?.data?.error || '转换失败，请重试';
      console.error('转换错误:', error);
    } finally {
      this.isConverting = false;
    }
  }

  downloadResult() {
    if (this.convertResult) {
      const link = document.createElement('a');
      link.href = this.convertResult.downloadUrl;
      link.download = this.convertResult.filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }

  resetForm() {
    this.selectedFile = null;
    this.sourceFormat = '';
    this.targetFormat = '';
    this.convertResult = null;
    this.errorMessage = '';
    this.convertProgress = 0;
    
    // 重置文件输入
    const fileInput = document.getElementById('fileInput');
    if (fileInput) {
      fileInput.value = '';
    }
  }

  getFormatIcon(format) {
    const formatObj = this.formats.find(f => f.value === format);
    return formatObj ? formatObj.icon : '📄';
  }

  getFormatLabel(format) {
    const formatObj = this.formats.find(f => f.value === format);
    return formatObj ? formatObj.label : format.toUpperCase();
  }

  getSelectedFileSize() {
    if (!this.selectedFile) return '';
    return configService.formatFileSize(this.selectedFile.size);
  }
} 